import { defineStore } from 'pinia'

export type Session = {
  userId: number | null
  accessToken: string | null
  refreshToken: string | null
  expiresTime: string | null
}

function load(): Session {
  return {
    userId: Number(localStorage.getItem('userId')) || null,
    accessToken: localStorage.getItem('accessToken'),
    refreshToken: localStorage.getItem('refreshToken'),
    expiresTime: localStorage.getItem('expiresTime')
  }
}

function persist(s: Session) {
  if (s.userId != null) localStorage.setItem('userId', String(s.userId))
  else localStorage.removeItem('userId')
  if (s.accessToken) localStorage.setItem('accessToken', s.accessToken)
  else localStorage.removeItem('accessToken')
  if (s.refreshToken) localStorage.setItem('refreshToken', s.refreshToken)
  else localStorage.removeItem('refreshToken')
  if (s.expiresTime) localStorage.setItem('expiresTime', s.expiresTime)
  else localStorage.removeItem('expiresTime')
}

export const useUserStore = defineStore('user', {
  state: () => ({ session: load() }),
  getters: {
    isLogin: (s) => !!s.session.accessToken
  },
  actions: {
    setSession(partial: Partial<Session>) {
      this.session = { ...this.session, ...partial }
      persist(this.session)
    },
    clear() {
      this.session = { userId: null, accessToken: null, refreshToken: null, expiresTime: null }
      persist(this.session)
    }
  }
})